from flask import Blueprint, current_app, request, jsonify, session, send_from_directory, render_template,send_file
from app.models.user import User, Message, Comment, Post,CoupleRelationship
import os
from datetime import datetime
import uuid
from werkzeug.utils import secure_filename
from app.extensions import db
api_bp = Blueprint('api_bp', __name__)





def get_user_relationship(user_id):
    """获取用户当前有效的情侣关系（已确认）"""
    return CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == user_id) |
         (CoupleRelationship.user2_id == user_id)) &
        (CoupleRelationship.status == 'accepted')
    ).first()
# 登录验证装饰器
def login_required(f):
    import functools

    @functools.wraps(f)
    def decorated_function(*args, **kwargs):
        receiver = User.query.filter_by(username=session.get("username")).first()
        if 'user_id' not in session or not receiver:
            return jsonify({'status': 'error', 'message': '请先登录'}), 401
        return f(*args, **kwargs)

    return decorated_function


def login_required_html(f):
    import functools

    @functools.wraps(f)
    def decorated_function(*args, **kwargs):
        receiver = User.query.filter_by(username=session.get("username")).first()
        if 'user_id' not in session or not receiver:
            return render_template('/error/401.html'), 401
        return f(*args, **kwargs)

    return decorated_function


# 检查文件类型
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS']


# 获取当前用户信息
@api_bp.route('/api/user', methods=['GET'])
@login_required
def get_current_user():
    user = User.query.get(session['user_id'])
    return jsonify({
        'id': user.id,
        'name': user.username,
        'nickname': user.nickname,
        'avatar': user.avatar if user.avatar else 'default_avatar.jpg'
    })


# 上传文件
@api_bp.route('/api/upload', methods=['POST'])
@login_required
def upload_file():
    if 'file' not in request.files:
        return jsonify({'status': 'error', 'message': '没有文件部分'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'status': 'error', 'message': '没有选择文件'}), 400

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # 添加时间戳和唯一ID避免文件名冲突
        timestamp = str(datetime.now().strftime('%Y%m%d%H%M%S'))[:8]
        unique_id = str(datetime.now().strftime('%Y%m%d%H%M%S'))[8::] + "_" + str(uuid.uuid4())[:8]
        filename = f"{unique_id}_{filename}"

        # 构建完整文件路径
        filepath = os.path.join(
            current_app.config['UPLOAD_FOLDER'].replace(os.sep, '/'),
            f"AccountId_{str(session['user_id'])}".replace(os.sep, '/'),
            str(timestamp),
            filename
        )

        # 关键：创建所有不存在的父目录（exist_ok=True表示目录存在也不报错）
        os.makedirs(os.path.dirname(filepath), exist_ok=True)

        # 现在可以安全保存文件了
        file.save(filepath)

        return jsonify({
            'status': 'success',
            'url': f'/static/uploads/AccountId_{str(session["user_id"])}/{str(timestamp)}/{filename}'
        })

    return jsonify({'status': 'error', 'message': '文件类型不允许'}), 400


@api_bp.route('/api/upload/<filename>', methods=['DELETE'])
@login_required
def delete_file(filename):
    # 验证文件名
    if not filename:
        return jsonify({'status': 'error', 'message': '文件名不能为空'}), 400

    # 安全检查：确保文件名包含当前用户ID，防止越权删除
    user_id = str(session['user_id'])
    if f'AccountId_{user_id}' not in filename:
        return jsonify({'status': 'error', 'message': '没有权限删除此文件'}), 403

    # 构建文件路径
    filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)

    # 检查文件是否存在并删除
    try:
        if os.path.exists(filepath):
            os.remove(filepath)
            return jsonify({'status': 'success', 'message': '文件已删除'})
        else:
            return jsonify({'status': 'error', 'message': '文件不存在'}), 404
    except Exception as e:
        current_app.logger.error(f"删除文件失败: {str(e)}")
        return jsonify({'status': 'error', 'message': '删除文件失败'}), 500

@api_bp.route('/api/music')
def get_music():
    MUSIC_FOLDER = os.path.join(current_app.config['UPLOAD_FOLDER'], 'music')
    os.makedirs(MUSIC_FOLDER, exist_ok=True)
    music_path = os.path.join(MUSIC_FOLDER, "background_music.mp3")
    
    # 检查文件是否存在
    if not os.path.exists(music_path):
        # 如果没有找到音乐文件，可以返回默认音乐或404
        return "音乐文件不存在", 404
        
    # 流式传输音乐文件
    return send_file(music_path, mimetype="audio/mpeg", as_attachment=False)





# 用户相关API
@api_bp.route('/api/users', methods=['GET'])
@login_required
def get_users():
    if "super_admin" == session['user_id']:
        users = User.query.all()
        return jsonify([{
            'id': user.id,
            'name': user.username,
            'nickname': user.nickname,
            'avatar': user.avatar if user.avatar else 'default_avatar.jpg'
        } for user in users])
    else:
        return jsonify({'status': 'error', 'message': '无权查看其他用户信息'}), 403


@api_bp.route('/api/users/<int:user_id>', methods=['PUT'])
@login_required
def update_user(user_id):
    if user_id != session['user_id']:
        return jsonify({'status': 'error', 'message': '无权修改其他用户信息'}), 403

    user = User.query.get(user_id)
    data = request.json
    if 'avatar' in data:
        # 构建文件路径
        normalized_path = os.path.normpath(current_app.config['UPLOAD_FOLDER'])
        uf_filepath = normalized_path.replace(os.sep, '/')
        prefix_to_remove = "/static/uploads/"
        avatar_path = user.avatar.replace(os.sep, '/')
        if avatar_path.startswith(prefix_to_remove):
            avatar_relative = avatar_path[len(prefix_to_remove):]
        else:
            # 如果没有前缀，直接使用（防止错误）
            avatar_relative = avatar_path
        filepath = os.path.join(uf_filepath, avatar_relative).replace(os.sep, '/')
        # 检查文件是否存在并删除
        try:
            if os.path.exists(filepath):
                os.remove(filepath)
                current_app.logger.error(f"删除头像: {filepath}")
        except Exception as e:
            current_app.logger.error(f"删除文件失败: {str(e)}")
        user.avatar = data['avatar']
        session['avatar'] = data['avatar']
    if 'nickname' in data:
        user.nickname = data['nickname']
        session['nickname'] = data['nickname']
    db.session.commit()
    return jsonify({'status': 'success'})


# 留言相关API
@api_bp.route('/api/messages', methods=['GET'])
@login_required
def get_messages():
    user_id = User.query.get(session['user_id']).id
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    filter_type = request.args.get('filter_type')  # 接收筛选类型参数

    # 构建基础查询：当前用户发送或接收的留言
    query = Message.query.filter(
        (Message.sender_id == user_id) | (Message.receiver_id == user_id)
    )
    # 应用筛选条件
    if filter_type == 'self':
        # 筛选给自己的留言：接收者是自己
        query = query.filter(Message.receiver_id == user_id)
    elif filter_type and filter_type.isdigit():
        # 筛选与特定用户（伴侣）相关的留言
        filter_user_id = int(filter_type)
        query = query.filter(
            (Message.receiver_id == filter_user_id)
            # (Message.sender_id == filter_user_id) | (Message.receiver_id == filter_user_id)
        )
    # 执行查询（按时间倒序）
    pagination = query.order_by(Message.created_at.desc()).paginate(
        page=page, per_page=per_page
    )
    messages = pagination.items

    result = []
    for msg in messages:
        sender = User.query.get(msg.sender_id)
        receiver = User.query.get(msg.receiver_id)
        result.append({
            'id': msg.id,
            'sender_id': msg.sender_id,
            'receiver_id': msg.receiver_id,
            'receiver_name': receiver.nickname,
            'content': msg.content,
            'parent_id': msg.parent_id,
            'name': sender.nickname,
            'avatar': sender.avatar,
            'created_at': msg.created_at.isoformat(),
            'updated_at': msg.updated_at.isoformat()
        })

    return jsonify({
        'messages': result,
        'pagination': {
            'total': pagination.total,
            'pages': pagination.pages,
            'page': page,
            'per_page': per_page,
            'has_next': pagination.has_next,
            'has_prev': pagination.has_prev
        }
    })


# 创建留言（支持回复功能）
@api_bp.route('/api/messages', methods=['POST'])
@login_required
def create_message():
    data = request.get_json()

    # 验证数据
    if not all(k in data for k in ('receiver_id', 'content')):
        return jsonify({'status': 'error', 'message': '缺少必要参数'}), 400

    # 创建新留言
    message = Message(
        sender_id=User.query.get(session['user_id']).id,
        receiver_id=data['receiver_id'],
        content=data['content'],
        parent_id=data.get('parent_id')  # 新增：支持回复功能
    )

    db.session.add(message)
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '留言发送成功',
        'message_id': message.id
    })


# 更新留言
@api_bp.route('/api/messages/<int:message_id>', methods=['PUT'])
@login_required
def update_message(message_id):
    message = Message.query.get_or_404(message_id)

    # 验证权限（只能修改自己发送的留言）
    if message.sender_id != User.query.get(session['user_id']).id:
        return jsonify({'status': 'error', 'message': '没有权限修改此留言'}), 403

    data = request.get_json()
    if 'content' in data and data['content'].strip():
        message.content = data['content']
        db.session.commit()
        return jsonify({'status': 'success', 'message': '留言已更新'})

    return jsonify({'status': 'error', 'message': '留言内容不能为空'}), 400


# 删除留言
@api_bp.route('/api/messages/<int:message_id>', methods=['DELETE'])
@login_required
def delete_message(message_id):
    message = Message.query.get_or_404(message_id)
    current_user = User.query.get(session['user_id'])
    # 验证权限（只能删除自己发送的或收到的留言）
    if message.sender_id != current_user.id and message.receiver_id != current_user.id:
        return jsonify({'status': 'error', 'message': '没有权限删除此留言'}), 403

    db.session.delete(message)
    db.session.commit()
    return jsonify({'status': 'success', 'message': '留言已删除'})


# 新增用户搜索接口
@api_bp.route('/api/users/search', methods=['GET'])
@login_required
def search_users():
    """
    搜索用户接口
    请求参数: username - 搜索关键词（用户名或昵称）
    返回: 匹配的用户列表
    """
    # 获取搜索关键词
    search_term = request.args.get('username', '').strip()

    # 如果搜索词为空，返回空列表
    if not search_term:
        return jsonify([])

    try:
        # 搜索用户名或昵称包含关键词的用户（排除当前登录用户）
        users = User.query.filter(
            (User.username.ilike(f'%{search_term}%') |
             User.nickname.ilike(f'%{search_term}%')) &
            (User.id != User.query.get(session['user_id']).id)
        ).limit(10).all()  # 限制最多返回10条结果

        # 格式化返回结果
        result = []
        for user in users:
            result.append({
                'id': user.id,
                'username': user.username,
                'nickname': user.nickname or user.username,  # 昵称不存在则用用户名
                'avatar': user.avatar or '/static/default_avatar.jpg'  # 头像不存在则用默认头像
            })

        return jsonify(result)

    except Exception as e:
        # 错误处理
        print(f"搜索用户时发生错误: {str(e)}")
        return jsonify({'status': 'error', 'message': '搜索失败'}), 500


@api_bp.route('/messages')
@login_required_html
def couple_page():
    """渲染情侣空间页面"""
    return render_template('messages.html')


# 静态文件服务
@api_bp.route('/static/uploads/<path:filename>')
def uploaded_file(filename):
    return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename)


@api_bp.route('/moments')
@login_required_html
def moments_page():
    """渲染情侣空间页面"""
    return render_template('moments.html')

@api_bp.route('/api/posts', methods=['GET', 'POST'])
@login_required
def api_posts():
    current_user_id = session['user_id']  # 获取当前登录用户ID
    
    if request.method == 'POST':
        # 创建新动态（保持不变，仅当前用户可创建自己的动态）
        content = request.json.get('content', '')
        image_url = request.json.get('image_url', '')

        post = Post(
            user_id=current_user_id,
            content=content,
            image_url=image_url
        )
        db.session.add(post)
        db.session.commit()

        return jsonify({'status': 'success', 'post_id': post.id})

    # 获取动态列表（仅自己和情侣的动态）
    try:
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        # 确保页码为正数并限制范围
        page = max(1, page)
        per_page = max(1, min(per_page, 100))  # 限制最大每页数量为100
    except ValueError:
        # 参数无效时使用默认值
        page = 1
        per_page = 10

    # 获取当前用户的情侣关系（已确认）
    relationship = get_user_relationship(current_user_id)
    # 确定情侣ID（如果存在）
    couple_id = None
    if relationship:
        couple_id = relationship.user2_id if relationship.user1_id == current_user_id else relationship.user1_id

    # 构建查询条件：动态所有者为当前用户或其情侣
    valid_owners = [current_user_id]
    if couple_id:
        valid_owners.append(couple_id)
    
    # 筛选符合条件的动态并按创建时间倒序排列
    posts_query = Post.query.filter(
        Post.user_id.in_(valid_owners)
    ).order_by(Post.created_at.desc())
    
    # 执行分页查询
    paginated = posts_query.paginate(page=page, per_page=per_page)

    # 处理返回数据
    posts = []
    for post in paginated.items:
        # 标记是否为当前用户自己的动态
        is_own = post.user_id == current_user_id

        # 获取评论数量（包含所有层级的评论）
        comment_count = len(post.comments)

        posts.append({
            'id': post.id,
            'content': post.content,
            'image_url': post.image_url,
            'created_at': post.created_at.isoformat(),
            'author': {
                'id': post.author.id,
                'nickname': post.author.nickname,
                'avatar': post.author.avatar
            },
            'is_own': is_own,
            'comment_count': comment_count
        })

    return jsonify({
        'posts': posts,
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total_pages': paginated.pages,
            'total_items': paginated.total,  # 新增：返回总条数，方便前端展示
            'has_next': paginated.has_next,
            'has_prev': paginated.has_prev  # 新增：是否有上一页
        }
    })

@api_bp.route('/api/posts/<int:post_id>', methods=['GET', 'PUT', 'DELETE'])
@login_required
def api_post(post_id):
    post = Post.query.get_or_404(post_id)
    current_user_id = session['user_id']  # 获取当前登录用户ID
    
    # 获取当前用户的情侣关系（已确认）
    relationship = get_user_relationship(current_user_id)
    # 确定情侣ID（如果存在）
    couple_id = None
    if relationship:
        couple_id = relationship.user2_id if relationship.user1_id == current_user_id else relationship.user1_id

    # 检查动态所有者是否为当前用户或其情侣（仅对GET请求做此限制，PUT/DELETE仍限制为自己的动态）
    if request.method == 'GET':
        valid_owners = [current_user_id]
        if couple_id:
            valid_owners.append(couple_id)
        # 若动态不属于自己或情侣，返回无权访问
        if post.user_id not in valid_owners:
            return jsonify({'status': 'error', 'message': '无权访问此动态'}), 403
    else:
        # PUT/DELETE操作仍限制为只能操作自己的动态
        if post.user_id != current_user_id:
            return jsonify({'status': 'error', 'message': '没有权限操作此动态'}), 403

    if request.method == 'GET':
        # 获取单条动态详情，包含评论
        comments = []
        for comment in post.comments:
            if not comment.parent_id:  # 只获取顶级评论
                replies = []
                for reply in comment.replies:
                    replies.append({
                        'id': reply.id,
                        'content': reply.content,
                        'created_at': reply.created_at.isoformat(),
                        'author': {
                            'id': reply.author.id,
                            'nickname': reply.author.nickname,
                            'avatar': reply.author.avatar
                        },
                        'is_own': reply.user_id == current_user_id  # 修正为当前用户ID判断
                    })

                comments.append({
                    'id': comment.id,
                    'content': comment.content,
                    'created_at': comment.created_at.isoformat(),
                    'author': {
                        'id': comment.author.id,
                        'nickname': comment.author.nickname,
                        'avatar': comment.author.avatar
                    },
                    'is_own': comment.user_id == current_user_id,  # 修正为当前用户ID判断
                    'replies': replies
                })

        return jsonify({
            'id': post.id,
            'content': post.content,
            'image_url': post.image_url,
            'created_at': post.created_at.isoformat(),
            'author': {
                'id': post.author.id,
                'nickname': post.author.nickname,
                'avatar': post.author.avatar
            },
            'is_own': post.user_id == current_user_id,  # 修正为当前用户ID判断
            'comments': comments
        })

    elif request.method == 'PUT':
        # 更新动态（仅自己的动态）
        content = request.json.get('content', '')
        post.content = content
        db.session.commit()
        return jsonify({'status': 'success'})

    elif request.method == 'DELETE':
        # 删除动态（仅自己的动态）
        normalized_path = os.path.normpath(current_app.config['UPLOAD_FOLDER'])
        uf_filepath = normalized_path.replace(os.sep, '/').replace("\\", "/").replace("\\\\", "/")
        prefix_to_remove = "/static/uploads/"
        avatar_path = post.image_url.replace(os.sep, '/')
        if avatar_path.startswith(prefix_to_remove):
            avatar_relative = avatar_path[len(prefix_to_remove):]
        else:
            avatar_relative = avatar_path
        filepath = os.path.join(uf_filepath, avatar_relative).replace(os.sep, '/')
        # 检查文件是否存在并删除
        try:
            if os.path.exists(filepath):
                os.remove(filepath)
                current_app.logger.error(f"删除动态图片: {filepath}")
        except Exception as e:
            current_app.logger.error(f"删除动态图片失败: {str(e)}")
        # 删除动态
        db.session.delete(post)
        db.session.commit()
        return jsonify({'status': 'success','message':'删除成功，动态图片已同步删除'})


@api_bp.route('/api/posts/<int:post_id>/comments', methods=['POST'])
@login_required
def api_add_comment(post_id):
    content = request.json.get('content', '')
    parent_id = request.json.get('parent_id')

    if not content:
        return jsonify({'status': 'error', 'message': '评论内容不能为空'}), 400

    comment = Comment(
        post_id=post_id,
        user_id=session['user_id'],
        content=content,
        parent_id=parent_id
    )
    db.session.add(comment)
    db.session.commit()

    return jsonify({'status': 'success', 'comment_id': comment.id})


@api_bp.route('/api/comments/<int:comment_id>', methods=['DELETE'])
@login_required
def api_delete_comment(comment_id):
    comment = Comment.query.get_or_404(comment_id)

    # 检查权限：只能删除自己的评论
    if comment.user_id != session['user_id']:
        return jsonify({'status': 'error', 'message': '没有权限删除此评论'}), 403

    db.session.delete(comment)
    db.session.commit()
    return jsonify({'status': 'success'})


@api_bp.route('/api/comments/<int:comment_id>', methods=['GET'])
@login_required
def get_comment(comment_id):
    comment = Comment.query.get_or_404(comment_id)
    # 验证权限（只能查看自己或自己动态的评论）
    post = Post.query.get(comment.post_id)
    if comment.user_id != session['user_id'] and post.user_id != session['user_id']:
        return jsonify({'status': 'error', 'message': '无权查看此评论'}), 403

    return jsonify({
        'id': comment.id,
        'content': comment.content,
        'created_at': comment.created_at.isoformat(),
        'parent_id': comment.parent_id,
        'is_own': comment.user_id == session['user_id'],
        'author': {
            'id': comment.author.id,
            'nickname': comment.author.nickname,
            'avatar': comment.author.avatar
        }
    })





# 上传背景图片
@api_bp.route('/api/upload/background', methods=['POST'])
@login_required
def upload_background():
    if 'file' not in request.files:
        return jsonify({'status': 'error', 'message': '没有文件部分'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'status': 'error', 'message': '没有选择文件'}), 400

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # 添加时间戳和唯一ID避免文件名冲突
        timestamp = str(datetime.now().strftime('%Y%m%d%H%M%S'))[:8]
        unique_id = str(datetime.now().strftime('%Y%m%d%H%M%S'))[8::] + "_" + str(uuid.uuid4())[:8]
        filename = f"{unique_id}_{filename}"

        # 构建完整文件路径
        filepath = os.path.join(
            current_app.config['UPLOAD_FOLDER'].replace(os.sep, '/'),
            f"backgrounds",
            f"AccountId_{str(session['user_id'])}",
            filename
        )

        # 创建所有不存在的父目录
        os.makedirs(os.path.dirname(filepath), exist_ok=True)

        # 保存文件
        file.save(filepath)

        # 对于情侣关系，保存背景图路径到关系记录中
        # 先检查是否有情侣关系
        relationship = CoupleRelationship.query.filter(
            ((CoupleRelationship.user1_id == session['user_id']) | 
             (CoupleRelationship.user2_id == session['user_id'])) &
            (CoupleRelationship.status == 'accepted')
        ).first()
        
        if relationship:
            # 更新关系记录中的背景图路径
            relationship.background_image = f'/static/uploads/backgrounds/AccountId_{str(session["user_id"])}/{filename}'
            db.session.commit()
            background_url = relationship.background_image
        else:
            # 没有情侣关系，只保存个人背景
            background_url = f'/static/uploads/backgrounds/AccountId_{str(session["user_id"])}/{filename}'
        
        return jsonify({
            'status': 'success',
            'url': background_url
        })

    return jsonify({'status': 'error', 'message': '文件类型不允许'}), 400


# 修改获取背景图片接口，确保返回默认值
@api_bp.route('/api/background', methods=['GET'])
@login_required
def get_background():
    # 默认背景图路径
    DEFAULT_BACKGROUND = '/uploads/bjtp.webp'
    
    # 检查是否有情侣关系
    relationship = CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == session['user_id']) | 
         (CoupleRelationship.user2_id == session['user_id'])) &
        (CoupleRelationship.status == 'accepted')
    ).first()
    
    if relationship and relationship.background_image:
        # 验证文件是否存在
        try:
            normalized_path = os.path.normpath(current_app.config['UPLOAD_FOLDER'])
            uf_filepath = normalized_path.replace(os.sep, '/')
            prefix_to_remove = "/static/uploads/"
            bg_path = relationship.background_image.replace(os.sep, '/')
            
            if bg_path.startswith(prefix_to_remove):
                bg_relative = bg_path[len(prefix_to_remove):]
                filepath = os.path.join(uf_filepath, bg_relative).replace(os.sep, '/')
                
                # 如果文件不存在，返回默认值
                if not os.path.exists(filepath):
                    return jsonify({
                        'status': 'success',
                        'url': DEFAULT_BACKGROUND
                    })
        except:
            # 处理路径解析错误，返回默认值
            return jsonify({
                'status': 'success',
                'url': DEFAULT_BACKGROUND
            })
        
        # 有有效背景图，返回该路径
        return jsonify({
            'status': 'success',
            'url': relationship.background_image
        })
    else:
        # 没有情侣关系或未设置背景图，返回默认
        return jsonify({
            'status': 'success',
            'url': DEFAULT_BACKGROUND
        })
    


# 删除背景图片，重置为默认
@api_bp.route('/api/background', methods=['DELETE'])
@login_required
def delete_background():
    # 检查是否有情侣关系
    relationship = CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == session['user_id']) | 
         (CoupleRelationship.user2_id == session['user_id'])) &
        (CoupleRelationship.status == 'accepted')
    ).first()
    
    if relationship and relationship.background_image:
        # 删除文件
        try:
            normalized_path = os.path.normpath(current_app.config['UPLOAD_FOLDER'])
            uf_filepath = normalized_path.replace(os.sep, '/')
            prefix_to_remove = "/static/uploads/"
            bg_path = relationship.background_image.replace(os.sep, '/')
            
            if bg_path.startswith(prefix_to_remove):
                bg_relative = bg_path[len(prefix_to_remove):]
                filepath = os.path.join(uf_filepath, bg_relative).replace(os.sep, '/')
                
                if os.path.exists(filepath):
                    os.remove(filepath)
        
        except Exception as e:
            current_app.logger.error(f"删除背景图片失败: {str(e)}")
        
        # 重置数据库记录
        relationship.background_image = None
        db.session.commit()
        return jsonify({'status': 'success', 'message': '背景图已重置为默认'})
    
    return jsonify({'status': 'error', 'message': '没有可删除的背景图'}), 404



